package com.wcl.demo.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.wcl.demo.R;
import com.wcl.demo.utils.overlayutil.PoiOverlay;
import com.wcl.demo.ui.activity.FindDetailActivity;
import com.wcl.demo.ui.adapter.FindAdapter;

import java.util.List;


/**
 * Created by dllo on 15/11/18.
 */
public class FindFragment extends BaseFragment implements View.OnClickListener {
    private MapView find_mapView;
    private BaiduMap map;//实现定位功能
    private LocationClient client;//实现LocationClient
    private RecyclerView find_recyclerView;
    private PoiSearch mPoiSearch = null;//定义检索
    private ImageView searchIv;//搜索
    private EditText keywordEt;//输入搜索的关键字
    private FindAdapter adapter;
    private LatLng ll;

    @Override
    protected int getLayout() {
        return R.layout.fragment_find;
    }

    @Override
    protected void initView() {

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        find_mapView = (MapView) view.findViewById(R.id.find_mapView);
        find_recyclerView = (RecyclerView) view.findViewById(R.id.find_recyclerView);
        searchIv = (ImageView) view.findViewById(R.id.searchIv);
        keywordEt = (EditText) view.findViewById(R.id.keywordEt);
        searchIv.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        adapter = new FindAdapter();
        GridLayoutManager manager = new GridLayoutManager(getContext(), 1);
        find_recyclerView.setAdapter(adapter);
        find_recyclerView.setLayoutManager(manager);

        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(1000);//每隔1秒扫描定位一次
        option.setCoorType("bd09ll");//设置坐标类型
        option.setOpenGps(true);//设置是否开启GPS
        option.setAddrType("all");//获取地址信息类型
        option.setIsNeedAddress(true);//获取地址信息
        client = new LocationClient(getContext());//初始化LocationClient定位客户端
        client.registerLocationListener(new MyFindLocationListenner());//注册监听回调对象
        client.setLocOption(option);//将定位服务设置到客户端
        client.start();//开启定位 = (MapView) findViewById(R.id.location_mapView);
        map = find_mapView.getMap();//得到Baidu地图
        map.setMyLocationEnabled(true);//开启定位功能
        client = new LocationClient(getContext());//初始化LocationClient定位客户端
        client.registerLocationListener(new MyFindLocationListenner());//注册监听回调对象


        mPoiSearch = PoiSearch.newInstance();//创建Poi检索实例
        OnGetPoiSearchResultListener listener = new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                //获取POI检索结果
                if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                    Toast.makeText(getContext(), "没有这个位置,请重新检索", Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.i("lanou4g", poiResult + "???????????????????");
                PoiOverlay overlay = new MyPoiOverlay(map);
                map.setOnMarkerClickListener(overlay);
                overlay.setData(poiResult);
                overlay.addToMap();
                overlay.zoomToSpan();
                List<PoiInfo> list = poiResult.getAllPoi();
                adapter.addData(list);
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
                //获取Place详情页检索结果
                if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(getContext(), "抱歉，未找到结果",
                            Toast.LENGTH_SHORT).show();
                } else {// 正常返回结果的时候，此处可以获得很多相关信息
                    Toast.makeText(getContext(),
                            poiDetailResult.getName() + ": " + poiDetailResult.getAddress(),
                            Toast.LENGTH_LONG).show();
                    Intent intent = new Intent();
                    String address = poiDetailResult.getAddress();
                    String name = poiDetailResult.getName();
                    String url = poiDetailResult.getDetailUrl();
                    String phone = poiDetailResult.getTelephone();
                    intent.putExtra("address" , address);
                    intent.putExtra("name" , name);
                    intent.putExtra("url" , url);
                    intent.putExtra("phone" , phone);
                    intent.setClass(getContext() , FindDetailActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }
            }

        };
        mPoiSearch.setOnGetPoiSearchResultListener(listener);//周边检索
    }

    /***
     * 实现逻辑
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * 定位SDK监听函数
     */
    public class MyFindLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || find_mapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())//纬度
                    .longitude(location.getLongitude()).build();//经度
            map.setMyLocationData(locData);

            ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            Log.i("sxxc", ll + "_________________");
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
            map.animateMapStatus(u);
        }
    }

    @Override
    public void onClick(View v) {
        //周边检索
        PoiNearbySearchOption option = new PoiNearbySearchOption();
        String keyWord = keywordEt.getText().toString();
        option.keyword(keyWord);
        option.location(ll);
        option.radius(10000);
        mPoiSearch.searchNearby(option);
    }

    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            // if (poi.hasCaterDetails) {
            mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                    .poiUid(poi.uid));
            // }
            return true;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        find_mapView.onDestroy();
        mPoiSearch.destroy();
        client.stop();
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        find_mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        find_mapView.onPause();
    }
}
